﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;

namespace FileUploadHelper
{
    public class BaseUpload_Image
    {
        #region 对象定义
        enum FileNameCreateType
        {
            ByGUID,
            ByDate,
            ByTime,
            ByDateTime,
            ByMillisecond
        }
        public struct Size
        {
            public Size(int w,int h)
            {
                Width = w;
                Height = h;
            }
            public int Width;
            public int Height;
        }
        #endregion
        #region 属性_Set
        /// <summary>
        /// 指定图片在服务器上的存储目录
        /// </summary>
        public string Folder { get; set; }
        private string _Extends = ".gif|.jpg|.png|.jpge";
        /// <summary>
        /// 支持上传的文件后缀
        /// </summary>
        public string Extends
        {
            get { return _Extends; }
            set { _Extends = value; }
        }
        private Size _CurrentSize = new Size(165,165);
        /// <summary>
        /// 设置当前图片大小
        /// </summary>
        public Size CurrentSize
        {
            get { return _CurrentSize; }
            set { _CurrentSize = value; }
        }
        /// <summary>
        /// 如果此属性不为空，上传原图后，再将图片按照此列表中的尺寸收缩生成多张图片。（只收缩，不放大）
        /// </summary>
        public List<Size> SizeList { get; set; }
        /// <summary>
        /// 如果此属性不为空，上传时，检查图片的尺寸，超出，则不上传。
        /// </summary>
        public Size MaxSize { get; set; }
        private long _MaxVolume = 1024 * 1024;
        /// <summary>
        /// 上传图片的最大体积（单位byte），默认为1M。
        /// </summary>
        public long MaxVolume
        {
            get { return _MaxVolume; }
            set { _MaxVolume = value; }
        }
        private FileNameCreateType _FileNameFrom = FileNameCreateType.ByGUID;
        /// <summary>
        /// 生成文件名的方式，默认为GUID。
        /// </summary>
        private FileNameCreateType FileNameFrom
        {
            get { return _FileNameFrom; }
            set { _FileNameFrom = value; }
        }
        #endregion
        #region Check
        /// <summary>
        /// 非空检查
        /// </summary>
        /// <returns></returns>
        public virtual string Check_IsNullOrEmpty(HttpPostedFile file)
        {
            if (file == null)
            {
                End("请选择文件！", false);
            }
            if (string.IsNullOrEmpty(file.FileName))
            {
                End("请选择文件！", false);
            }
            //检查必备属性是否已设置
            if (string.IsNullOrEmpty(Folder))
            {
                End("请指定图片在服务器上的存储目录！", false);
            }
            return file.FileName;
        }
        /// <summary>
        /// 检查文件类型
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public virtual string Check_FileType(string fileName)
        {
            if (!fileName.Contains("."))
            {
                End("请上传正确的图片！", false);
            }
            string suffix = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
            if (!("|" + _Extends + "|").ToLower().Contains("|" + suffix + "|"))
            {
                End("请上传正确的图片！",false);
            }
            return suffix;
        }

        
        #endregion


        #region Flow
        public virtual void DoFlow()
        {
            HttpPostedFile file = HttpContext.Current.Request.Files["Filedata"];
            string fileName = Check_IsNullOrEmpty(file);
            string suffix = Check_FileType(fileName);
            string newName = Get_FileName();
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(Folder)))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(Folder));
            }
            string path = HttpContext.Current.Server.MapPath(Folder + newName + suffix);
            file.SaveAs(path);
            End(newName + suffix, true);
        }
        public void End(string msg, bool flag)
        {
            string str = (flag ? "1" : "0") + "|" + msg;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(str);
            HttpContext.Current.Response.End();
        }
        private string Get_FileName()
        {
            string result = string.Empty;
            lock (result)
            {
                switch (FileNameFrom)
                {
                    case FileNameCreateType.ByGUID:
                        result = Guid.NewGuid().ToString();
                        break;
                    case FileNameCreateType.ByDate:
                        result = DateTime.Now.ToString("yyyyMMdd");
                        break;
                    case FileNameCreateType.ByTime:
                        result = DateTime.Now.ToString("HHmmss");
                        break;
                    case FileNameCreateType.ByDateTime:
                        result = DateTime.Now.ToString("yyyyMMddHHmmss");
                        break;
                    case FileNameCreateType.ByMillisecond:
                        DateTime d1 = DateTime.Now;
                        DateTime d2 = new DateTime(1970, 1, 1, 0, 0, 0);
                        TimeSpan span = d1 - d2;
                        result = span.TotalMilliseconds.ToString();
                        break;
                }
            }
            return result;
        }
        #endregion
    }
}
